package cn.element.leetcode.common;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.LongAdder;

/**
 * @description:
 * @author: gonghongwei
 * @create: 2021-11-29 17:05
 */
public class ThreadTest {

	//	private static AtomicInteger ai = new AtomicInteger(0);
	private static LongAdder longAdder = new LongAdder();

	private static class AtomicPrintTask implements Runnable {
		private String letter;
		private int targetState;
		private int total;

		public AtomicPrintTask(String letter, int targetState, int total) {
			this.letter = letter;
			this.targetState = targetState;
			this.total = total;
		}

		@Override
		public void run() {
			while (longAdder.intValue() < total) {
				int currValue = longAdder.intValue();
				//非原子，会导致多打印，做一个判断
				if (currValue < 30 && currValue % 3 == targetState) {
					System.out.print(letter);
					longAdder.increment();
				}
			}
		}
	}

	public static void main(String[] args) {
//		ExecutorService pool = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
		ThreadPoolExecutor pool = new ThreadPoolExecutor(Runtime.getRuntime().availableProcessors() + 1, 2 * Runtime.getRuntime().availableProcessors() + 1,
				50L, TimeUnit.MILLISECONDS,
				new LinkedBlockingQueue<Runnable>(), new ThreadPoolExecutor.CallerRunsPolicy());

		pool.submit(new AtomicPrintTask("A", 0, 30));
		pool.submit(new AtomicPrintTask("B", 1, 30));
		pool.submit(new AtomicPrintTask("C", 2, 30));

		pool.shutdown();
	}

}
